package Concurrent;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Description：
 * Author: zhangc
 * Date：2017/10/7 15:48
 */
public class ThreadLocalTest {

    private final static ThreadLocal<Integer> local = new ThreadLocal<Integer>() {
        @Override
        protected Integer initialValue() {
            return 0;
        }
    };

    private static AtomicInteger integer = new AtomicInteger(0);
    private static ExecutorService service = Executors.newFixedThreadPool(10, new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            return new Thread(new Th(integer.getAndIncrement() + " "));
        }
    });

    static class Th implements Runnable {

        private String name;

        public Th() {
        }

        public Th(String name) {
            this.name = name;
        }

        @Override
        public void run() {
            while (true) {
                local.set(local.get().intValue() + 1);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + " : " + local.get());
            }
        }
    }

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            service.execute(new Th());
        }
    }

}
